package com.idle.util;

import java.io.InputStream;
import java.net.URL;

import android.R.integer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;

public class BitmapUtil {
	public static BitmapFactory.Options getOptions() {
		BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 1;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];
		return options;
	}
	
	public static BitmapFactory.Options getOptions(Context mContext, Uri mUri,
			int desWidth, int desHeight) {
		BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        decode(mContext, mUri, options);
        int scale = 1;
        while (checkSize(options.outWidth / scale > desWidth, 
        		options.outHeight / scale > desHeight, false)) {
            scale++;
        }
        options.inJustDecodeBounds = false;
        options.inSampleSize = scale;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];
		return options;
	}

	private static boolean checkSize(boolean widthBigger, boolean heightBigger, boolean isCropCenter) {
        if (isCropCenter) {
            return widthBigger && heightBigger;
        } else {
            return widthBigger || heightBigger;
        }
    }
	
	public static Bitmap decode(Context mContext, Uri mUri, BitmapFactory.Options options) {
        try {
            InputStream inputStream;
            if (mUri.getScheme().startsWith("http") || mUri.getScheme().startsWith("https")) {
                inputStream = new URL(mUri.toString()).openStream();
            } else {
                inputStream = mContext.getContentResolver().openInputStream(mUri);
            }
            return BitmapFactory.decodeStream(inputStream, null, options);
        } catch (OutOfMemoryError e) {
        	System.gc();
        	e.printStackTrace();
        	Log.w("OOM", "inSampleSize:"+options.inSampleSize);
        	options.inSampleSize++;
        	return decode(mContext, mUri, options);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	
	public static Bitmap scaledBitmap(Bitmap bitmap, int width, int height) {
		Bitmap  temp = null;
		try {
			temp = Bitmap.createScaledBitmap(bitmap, width, 
					height, true);
		} catch (OutOfMemoryError e) {
			System.gc();
        	e.printStackTrace();
        	Log.w("OOM", "scaledBitmap:width:"+width+" height:"+height);
		}
		return temp;
	}
	
}
